#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use std::sync::Arc;
use tokio::sync::Mutex as TokioMutex;
use std::sync::Mutex;
use anyhow::Result;
use log::{debug, info, warn, error};
use ai_trade_lib::compute::{
    indicators::AdvancedIndicatorCalculator,
    memory::{MemoryPool, MemoryPoolConfig},
    parallel::DataPipeline,
};
use ai_trade_lib::config::memory_config;
use ai_trade_lib::controller::{splash, system_config, };
use ai_trade_lib::service::stock_candle_service::{CandleQueryParams, StockCandleService};
use ai_trade_lib::GLOBAL_POOL;


#[tauri::command]

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 初始化内存配置
    memory_config::init_memory_config();

    // 初始化日志
    let exe_dir = std::env::current_exe()
        .unwrap_or_else(|_| std::path::PathBuf::from("."))
        .parent()
        .unwrap_or_else(|| std::path::Path::new("."))
        .to_path_buf();
    let log_config_path = exe_dir.join("config/log4rs.yaml");
    
    // 确保日志目录存在
    let log_dir = exe_dir.join("logs");
    if !log_dir.exists() {
        std::fs::create_dir_all(&log_dir).expect("Failed to create logs directory");
    }
    
    // 尝试使用 log4rs 配置文件，如果失败则使用默认配置
    if let Err(e) = log4rs::init_file(&log_config_path, Default::default()) {
        println!("Failed to initialize log4rs with config file: {}. Path: {:?}", e, log_config_path);
        // 设置默认的日志配置
        let stdout = log4rs::append::console::ConsoleAppender::builder().build();
        let file = log4rs::append::rolling_file::RollingFileAppender::builder()
            .build(
                log_dir.join("rust.log"),
                Box::new(log4rs::append::rolling_file::policy::compound::CompoundPolicy::new(
                    Box::new(log4rs::append::rolling_file::policy::compound::trigger::size::SizeTrigger::new(50 * 1024 * 1024)), // 50MB
                    Box::new(log4rs::append::rolling_file::policy::compound::roll::fixed_window::FixedWindowRoller::builder()
                        .build("logs/rust_{}.log", 5)
                        .expect("Failed to initialize log roller"))
                ))
            )
            .expect("Failed to initialize file appender");

        let config = log4rs::Config::builder()
            .appender(log4rs::config::Appender::builder().build("stdout", Box::new(stdout)))
            .appender(log4rs::config::Appender::builder().build("file", Box::new(file)))
            .build(log4rs::config::Root::builder()
                .appender("stdout")
                .appender("file")
                .build(log::LevelFilter::Debug))
            .expect("Failed to build log config");

        log4rs::init_config(config).expect("Failed to initialize logging");
    }

    info!("Starting AI Trade application");

    // 初始化数据库连接池
    let _ = &*GLOBAL_POOL;

    // 初始化依赖组件 
    let indicators = Arc::new(Mutex::new(AdvancedIndicatorCalculator::new(20))); // 使用20作为默认窗口大小
    let memory_pool = Arc::new(Mutex::new(MemoryPool::new(None)));
    let data_pipeline = Arc::new(DataPipeline::new(4)); // 使用4个线程

   

    // 启动Tauri应用
    tauri::Builder::default()
        .invoke_handler(tauri::generate_handler![
            splash::close_splashscreen,
            system_config::get_system_config,// 新增这一行
        ])
        .setup(|app| {
            let app_handle = app.handle();
            info!("AI Trade application setup complete");
            Ok(())
        })
        .run(tauri::generate_context!())?;

    Ok(())
}